<?php

namespace app\index\controller;

use app\model\Member;
use app\model\Sms;
use app\model\Users;
use app\service\PlatFormFactory;
use think\exception\ValidateException;
use app\model\Config;
use app\model\UuidRelation;
use app\model\Openid;
use think\facade\Cache;
use think\facade\Db;
use think\response\Json;
use EasyWeChat\Factory;

class AuthController extends Base
{
    public function openid()
    {
        $config = Config::getconfig('miniprogram');
        $code = input('code');
        if(!$code) {
            return $this->json([
                'errno' => 1,
                'msg' => '缺少参数'
            ]);
        }

        if (input('provide') == 'toutiao') {
            $url = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
            $client = new \GuzzleHttp\Client();
            $response = $client->post($url, [
                'json' => [
                    'appid' => $config['ttapp_id'],
                    'secret' => $config['ttsecret'],
                    'code' => $code,
                ]
            ]);
            $res = json_decode($response->getBody(), true);
            if ($res['err_no']) {
                return $this->json([
                    'errno' => 1,
                    'msg' => $res['err_tips']
                ]);
            }
            $member_info = Member::where('tt_mp_openid', $res['data']['openid'])->find();
        }else if (input('provide') == 'weixin') {
            $config = [
                'app_id' => $config['app_id'],
                'secret' => $config['secret'],
            ];

            $app = Factory::miniProgram($config);

            $res = $app->auth->session($code);
            $member_info = Member::where('wx_mp_openid', $res['openid'])->find();
        }else{
            $app = \EasyWeChat\Factory::officialAccount([
                'app_id' => $config['weixin_offiaccount_app_id'],
                'secret' => $config['weixin_offiaccount_secret'],
            ]);
            $user = $app->oauth->userFromCode($code);
            if (!$user->getId()) {
                return $this->json([
                    'errno' => 1,
                    'msg' => $user['errmsg']
                ]);
            }
            $member_info = Member::where('wx_service_openid', $user->getId())->find();
        }


        if($member_info) {
            return $this->json([
                'errno' => 0,
                'data' => $this->loginSuccess($member_info->toArray())
            ]);
        }else{
            return $this->json([
                'errno' => 1,
                'data' => []
            ]);
        }
    }

    // 绑定微信小程序openid
    public function bindWxMpOpenid()
    {
        $config = Config::getconfig('miniprogram');
        $config = [
            'app_id' => $config['app_id'],
            'secret' => $config['secret'],
        ];
        $app = Factory::miniProgram($config);

        $code = input('code');
        $res = $app->auth->session($code);
        $member_info = Member::where('id', UID())->find();
        $member_info->save([
            'wechat_openid' => $res['openid'],
            'wx_mp_openid' => $res['openid'],
        ]);

        return $this->json([
            'errno' => 0,
            'data' => $this->loginSuccess($member_info->toArray())
        ]);
    }

    // 绑定微信公众号openid
    public function bindWxServiceOpenid()
    {
        $config = Config::getconfig('miniprogram');

        $app = \EasyWeChat\Factory::officialAccount([
            'app_id' => $config['weixin_offiaccount_appid'],
            'secret' => $config['weixin_offiaccount_appsecret'],
        ]);

        $user = $app->oauth->userFromCode(input('code'));
        if(!$user->getId()) {
            return $this->json([
                'errno' => 1,
                'msg' => $user['errmsg'],
                'data' => []
            ]);
        }

        $member_info = Member::where('id', UID())->find();
        $member_info->save([
            'wx_service_openid' => $user->getId(),
        ]);

        return $this->json([
            'errno' => 0,
            'data' => $this->loginSuccess($member_info->toArray())
        ]);
    }

    // 绑定抖音小程序openid
    public function bindTtMpOpenid()
    {
        $config = Config::getconfig('miniprogram');

        $url = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
        $client = new \GuzzleHttp\Client();
        $response = $client->post($url, [
            'json' => [
                'appid' => $config['toutiao_mp_appid'],
                'secret' => $config['toutiao_mp_appsecret'],
                'code' => input('code'),
            ]
        ]);
        $res = json_decode($response->getBody(), true);
        if($res['err_no']) {
            return $this->json([
                'errno' => 1,
                'msg' => $res['err_tips'],
                'data' => []
            ]);
        }

        $member_info = Member::where('id', UID())->find();
        $member_info->save([
            'tt_mp_openid' => $res['data']['openid'],
        ]);
        return $this->json([
            'errno' => 0,
            'data' => $this->loginSuccess($member_info->toArray())
        ]);
    }


}
